<?php
require('common.php');

function add_var_uri($key)
{
	if ($key == 'tables')
	{
		$uri = "new_table.php";
	} else {
		$uri = 'add_variable.php?';
		global $domain;
		$uri .= ($key != $domain) ? "table=$key" : "domain=$domain";
	}
	return $uri;
}

function edit_var_uri($key, $name)
{
	if ($key == 'tables')
	{
		$uri = "edit_table.php?table=$name";
	} else {
		$uri = 'edit_variable.php?name=' . $name . "&";
		global $domain;
		$uri .= ($key != $domain) ? "table=$key" : "domain=$domain";
	}
	return $uri;
}

// BEGIN EXECUTION
html_header("variables");
?>

<body>

<div id="container">

<?php header_div(); ?>

<div id="body">

<?php

// build an array with all of the variables available to this user as normal variables in this domain 
$result = sql_exec("SELECT Name FROM Variables WHERE User='$user' AND (Domain='$domain' OR Domain IS NULL) ORDER BY Domain, Name");

// blocks is an array that will hold arrays
$blocks = array();
$blocks[$domain] = array();

while ($row = mysql_fetch_array($result))
{	
	array_push($blocks[$domain], $row['Name']);
}

// find all the tables 
$userno = user() . 'no';
$result = sql_exec("SHOW TABLES LIKE '$userno%' ");

// make array to hold tables
$blocks['tables'] = array();

while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
	$field = array_pop($row);
	array_push($blocks['tables'], $field);
}

// go through the array of variables just made ($blocks) and add each variable to $svg
foreach ($blocks as $key=>$variables)
{

	$num = count($variables);
	$adjust = 0;
	
	if ($key == 'tables')
	{
		echo "<h4>tables</h4>\n";
		if ($num == 0)
		{
			echo "<p>there are no tables.</p>\n";
		}
		echo "<p><a href=\"new_table.php\">add a table</a></p>\n";
	} else {
		echo "<h4>this page's variables</h4>\n";
		if ($num == 1) // wtf?
		{
			echo "<p>there are no variables.</p>\n";
		} 
		echo "<p><a href=\"add_variable.php?domain=$domain\">add a variable</a></p>\n";
	}
	
	echo "<ul>\n";
	for ($counter = 0; $counter < $num; $counter++)
	{
		// to fix the problem of displaying stuff like: it\'s a variable
		$button_text = stripslashes($variables[$counter]);
		if (!empty($button_text)) 
		{
			if ($key != 'Form Input')
			{
				$uri = ($button_text == '[ Add ]') ? add_var_uri($key) : edit_var_uri($key, $button_text);
			} else {
				$uri = '';
			}
			$button_text = remove_userno($button_text);
			echo "<li><a href=\"$uri\">$button_text</a></li>\n";
		} 
	} // end for
	echo "</ul>\n";
}

echo "<h4>other stuff</h4>\n";
echo "<p><a href=\"edit_page.php?domain=$domain\">back to editing</a></p>\n";
echo "<p><a href=\"index.php\">back home</a></p>\n";

echo footer(); ?>

</div>



</div>
</body>
</html>
